<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:insert="~{include :: header('发送消息')}" />
    <th:block th:insert="~{include :: summernote-css}" />
	<th:block th:insert="~{include :: ztree-css}" />
    <style>
        .target-type-group {
            margin-bottom: 15px;
        }
        .target-input {
            margin-top: 10px;
        }
        .template-select {
            margin-bottom: 15px;
        }
    </style>
</head>
<body class="white-bg">
    <div class="wrapper wrapper-content animated fadeInRight ibox-content">
        <form class="form-horizontal m" id="form-message-send">
            <div class="form-group">
                <label class="col-sm-2 control-label is-required">消息标题：</label>
                <div class="col-sm-10">
                    <input id="title" name="title" class="form-control" type="text" required>
                </div>
            </div>
            
            <div class="form-group">
                <label class="col-sm-2 control-label is-required">消息类型：</label>
                <div class="col-sm-10">
                    <select name="messageType" class="form-control m-b" th:with="type=${@dict.getType('sys_message_type')}" required>
                        <option value="">请选择</option>
                        <option th:each="dict : ${type}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>
                    </select>
                </div>
            </div>
            
            <div class="form-group">
                <label class="col-sm-2 control-label">优先级：</label>
                <div class="col-sm-10">
                    <select name="priority" class="form-control m-b" th:with="priority=${@dict.getType('sys_message_priority')}">
                        <option th:each="dict : ${priority}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>
                    </select>
                </div>
            </div>
            
            <div class="form-group">
                <label class="col-sm-2 control-label">发送方式：</label>
                <div class="col-sm-10">
                    <select name="sendMethod" class="form-control m-b" th:with="method=${@dict.getType('sys_message_method')}">
                        <option th:each="dict : ${method}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>
                    </select>
                </div>
            </div>
            
            <div class="form-group">
                <label class="col-sm-2 control-label is-required">发送范围：</label>
                <div class="col-sm-10">
					<div class="target-type-group">
					    <select name="targetType" class="form-control" id="targetType" th:with="target=${@dict.getType('sys_message_target')}">
					        <option th:each="dict : ${target}" th:text="${dict.dictLabel}" th:value="${dict.dictValue}"></option>
					    </select>
					</div>
					<div class="target-type-group" id="user-group" style="display: none;">
					    <select name="userid" class="form-control" id="userid">
							<option value="0">全部</option>
					        <option th:each="user : ${userList}" th:text="${user.userName +'('+ user.loginName +')'}" th:value="${user.userId}"></option>
					    </select>
					</div>
					<div class="target-type-group" id="role-group" style="display: none;">
					    <select name="roleid" class="form-control" id="roleid">
							<option value="0">全部</option>
					        <option th:each="role : ${roleList}" th:text="${role.roleName}" th:value="${role.roleId}"></option>
					    </select>
					</div>
					<div class="target-type-group" id="post-group" style="display: none;">
					    <select name="postid" class="form-control" id="postid">
							<option value="0">全部</option>
					        <option th:each="post : ${positions}" th:text="${post.postName +'('+ post.postCode +')'}" th:value="${post.postId}"></option>
					    </select>
					</div>
					<div class="form-group" id="dept-group" style="display: none;">
						<div class="col-sm-8">
						    <div id="tree" class="ztree ztree-border"></div>
						</div>
					</div>
                </div>
            </div>
            
            <div class="form-group template-select">
                <label class="col-sm-2 control-label">使用模板：</label>
                <div class="col-sm-10">
                    <select id="templateSelect" class="form-control">
                        <option value="">不使用模板</option>
                        <option th:each="template : ${templates}" th:text="${template.templateName}" th:value="${template.templateCode}"></option>
                    </select>
                </div>
            </div>
            
            <div class="form-group">
                <label class="col-sm-2 control-label">消息内容：</label>
                <div class="col-sm-10">
                    <div class="summernote"></div>
                </div>
            </div>
            
            <div class="form-group">
                <label class="col-sm-2 control-label">业务信息：</label>
                <div class="col-sm-10">
                    <div class="row">
                        <div class="col-sm-6">
                            <input type="text" name="businessType" class="form-control" placeholder="业务类型">
                        </div>
                        <div class="col-sm-6">
                            <input type="text" name="businessId" class="form-control" placeholder="业务ID">
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="form-group">
                <label class="col-sm-2 control-label">过期时间：</label>
                <div class="col-sm-10">
                    <input type="text" name="expireTime" class="form-control datetimepicker" placeholder="选择过期时间">
                </div>
            </div>
        </form>
    </div>
    
    <th:block th:insert="~{include :: footer}" />
    <th:block th:insert="~{include :: summernote-js}" />
    <th:block th:insert="~{include :: datetimepicker-js}" />
	<th:block th:insert="~{include :: ztree-js}" />
	<script th:src="@{/js/upload.js}"></script>
    
    <script type="text/javascript">
        var prefix = ctx + "system/message";
        
        $(function() {
			queryDeptTree();
            // 初始化富文本编辑器
            $('.summernote').summernote({
                placeholder: '请输入消息内容',
                height: 300,
                lang: 'zh-CN',
                followingToolbar: false,
                dialogsInBody: true,
                callbacks: {
                    onImageUpload: function(files) {
                        sendFile(files[0], this);
                    }
                }
            });
            
            // 初始化日期选择器
            $('.datetimepicker').datetimepicker({
                format: 'yyyy-mm-dd hh:ii:ss',
                autoclose: true,
                todayBtn: true
            });
            
            // 模板选择事件
            $('#templateSelect').change(function() {
                var templateCode = $(this).val();
                if (templateCode) {
                    $.ajax({
                        url: prefix + "/template/render/" + templateCode,
                        type: "get",
                        dataType: "json",
                        success: function(result) {
                            if (result.code == web_status.SUCCESS) {
                                $('.summernote').summernote('code', result.data);
                            } else {
                                $.modal.alertError(result.msg);
                            }
                        }
                    });
                }
            });
            
            // 目标类型变化事件 - 联动显示对应的选择框
            $('#targetType').change(function() {
                var targetType = $(this).val();
                
                // 隐藏所有选择框
                $('#user-group').hide();
                $('#role-group').hide();
                $('#post-group').hide();
                $('#dept-group').hide();
                
                // 根据选择显示对应的选择框
                switch(targetType) {
                    case '1': // 个人
                        $('#user-group').show();
                        break;
                    case '2': // 角色
                        $('#role-group').show();
                        break;
                    case '3': // 部门
                        $('#dept-group').show();
                        break;
                    case '4': // 岗位
                        $('#post-group').show();
                        break;
                    case '5': // 全体
                        // 全体用户不需要显示具体选择框
                        break;
                }
            });
            
            // 初始化时触发一次change事件，确保正确的初始显示状态
            $('#targetType').trigger('change');
        });
        
        // 上传文件
        function sendFile(file, obj) {
            var data = new FormData();
            data.append("file", file);
            $.ajax({
                type: "POST",
                url: ctx + "common/upload",
                data: data,
                cache: false,
                contentType: false,
                processData: false,
                dataType: 'json',
                success: function(result) {
                    if (result.code == web_status.SUCCESS) {
                        $(obj).summernote('editor.insertImage', result.url, result.fileName);
                    } else {
                        $.modal.alertError(result.msg);
                    }
                },
                error: function(error) {
                    $.modal.alertWarning("图片上传失败。");
                }
            });
        }
        
        $("#form-message-send").validate({
            focusCleanup: true
        });

		function queryDeptTree(){
			var url = ctx + "system/user/deptTreeData";
			var options = {
		        url: url,
				check: { enable: true },
		        expandLevel: 2
		    };
			$.tree.init(options);
			
			function zOnClick(event, treeId, treeNode) {
				$("#deptId").val(treeNode.id);
				$("#parentId").val(treeNode.pId);
				$.table.search();
			}
		}
        
        function submitHandler() {
            if ($.validate.form()) {
                var contentHTML = $('.summernote').summernote('code');
				var content = '';
				// 检查是否为空内容（去除HTML标签后检查）
				var textContent = contentHTML.replace(/<[^>]*>/g, '').trim();
				if (textContent === '' || contentHTML === '<p><br></p>' || contentHTML === '<p></p>') {
					content = '';
				} else {
					// 处理base64图片
					processBase64Images(contentHTML, function(processedHTML) {
						content = processedHTML;
					});
				}
                
                // 根据目标类型获取对应的值
                var targetType = $('#targetType').val();
                var targetIds = '';
                
                switch(targetType) {
                    case '1': // 个人
                        targetIds = $('#userid').val();
                        break;
                    case '2': // 角色
                        targetIds = $('#roleid').val();
                        break;
                    case '3': // 部门
                        // 部门需要从树形控件获取选中的节点
                        var nodes = $.tree.getCheckedNodes();
                        if (nodes && nodes.length > 0) {
                            targetIds = '[' + nodes.map(function(node) { return node.id; }).join(',') + ']';
                        } else {
                            targetIds = '[0]'; // 默认全部
                        }
                        break;
                    case '4': // 岗位
                        targetIds = $('#postid').val();
                        break;
                    case '5': // 全体
                        targetIds = '[0]';
                        break;
                }
                
                // 使用JSON格式提交数据
				/*
                var formData = {
                    title: $('#title').val(),
                    content: sHTML,
                    messageType: $('select[name="noticeType"]').val(),
                    priority: $('select[name="priority"]').val(),
                    sendMethod: $('select[name="sendMethod"]').val(),
                    targetType: targetType,
                    targetIds: targetIds,
                    templateSelect: $('#templateSelect').val(),
                    businessType: $('input[name="businessType"]').val(),
                    businessId: $('input[name="businessId"]').val(),
                    expireTime: $('input[name="expireTime"]').val()
                };
				*/
				var formData = $('#form-message-send').serializeArray();
				formData.push({name: 'targetIds', value: targetIds});
				formData.push({"name": "content", "value": content});
				console.log(formData);
				$.operate.save(prefix + "/send", formData);

            }
        }
    </script>
</body>
</html>